using System;
using Microsoft.SPOT;

namespace A6281 {
	public class ChipColorSet : ICyclicEnumerable {

		public ChipColorSet( params ChipColor[] chipColorArray ) : this( 0, chipColorArray ) {}

		public ChipColorSet( uint startingIndex, params ChipColor[] chipColorArray ) {
			if ( startingIndex >= chipColorArray.Length )
				throw new ArgumentOutOfRangeException( "startingIndex" );
			lock ( this.chipColorArraySync ) {
				this.chipColorArray = chipColorArray;
				this.startingIndex = startingIndex;
			}
		}

		public System.Collections.IEnumerator GetEnumerator() {
			return new ChipColorSetEnumerator( this );
		}

		public uint GetChipColorLength() {
			lock( this.chipColorArraySync ) {
				return ( uint )this.chipColorArray.Length;
			}
		}

		public ChipColor GetChipColorByIndex( uint index ) {
			if ( index >= this.chipColorArray.Length )
				throw new ArgumentOutOfRangeException( "startingIndex" );

			lock( this.chipColorArraySync ) {
				return this.chipColorArray[ index ];
			}
		}

		internal class ChipColorSetEnumerator : ICyclicEnumerator {

			public ChipColorSetEnumerator( ChipColorSet mother ) {
				this.mother = mother;
				this.Reset();
			}

			public object Current {
				get { return this.mother.GetChipColorByIndex( this.index ); }
			}

			public bool MoveNext() {
				this.index = ( uint )( this.index + 1 ) % this.mother.GetChipColorLength();
				return true; // will always have more because we cycle through from end to beginning
			}

			public void Reset() {
				this.index = ( this.mother.GetChipColorLength() - this.mother.startingIndex ) % this.mother.GetChipColorLength();
			}

			protected ChipColorSet mother;
			protected uint index;
		}

		protected object chipColorArraySync = new object();
		protected ChipColor[] chipColorArray;
		protected uint startingIndex;
	}
}
